<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-row>
        <el-alert title="添加商品信息" type="info" center show-icon></el-alert>
      </el-row>
      <el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        ref="addFormRef"
        :model="addFormList"
        :rules="addFormRules"
        label-width="80px"
        label-position="top"
      >
        <el-tabs
          v-model="activeIndex"
          tab-position="left"
          :before-leave="beforeLeave"
          @tab-click="changeTabs"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addFormList.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addFormList.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="number" v-model="addFormList.goods_weight"></el-input>
            </el-form-item>
            <el-form-item type="number" label="商品数量" prop="goods_number">
              <el-input v-model="addFormList.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addFormList.goods_cat"
                :options="cateList"
                :props="catePropas"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="item in manyList" :key="item.attr_id" :label="item.attr_name">
              <el-checkbox-group v-model="item.cp1_attr_vals">
                <el-checkbox :label="value" border v-for="(value,i) in item.cp2_attr_vals" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyList" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              :action="actionURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              list-type="picture"
              :headers="headersObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor ref="myQuillEditor" v-model="addFormList.goods_introduce"/>
            <el-button type="primary" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <!-- 图片预览图 -->
      <el-dialog title="提示" :visible.sync="picDialogVisible" width="50%">
        <img :src="previewPath" class="imgwidth">
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import _ from "lodash";
export default {
  data() {
    return {
      activeIndex: "0",
      addFormList: {
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 商品所属分类
        goods_cat: [],
        // 图片路径
        pics: [],
        // 商品描述
        goods_introduce: "",
        // 商品参数
        attrs: []
      },
      // 添加商品数据验证
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" }
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" }
        ]
      },
      // 分类列表
      cateList: [],
      // 分类规则
      catePropas: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover"
      },
      // 参数列表
      manyList: [],
      // 属性列表、
      onlyList: [],
      // 上传列表
      fileList: [],
      // 图片上传地址
      actionURL: "http://127.0.0.1:8888/api/private/v1/upload",
      // 请求头
      headersObj: {
        Authorization: window.sessionStorage.getItem("token")
      },
      // 图片名称
      previewPath: "",
      picDialogVisible: false
    };
  },
  created() {
    this.getcateList();
  },
  computed: {
    cateId() {
      if (this.addFormList.goods_cat.length === 3) {
        return this.addFormList.goods_cat[2];
      }
      return null;
    }
  },
  methods: {
    // 获取商品分类数据
    async getcateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) return this.$message.error("获取分类失败");
      this.cateList = res.data;
      // console.log(this.cateList);
    },
    // 分类级联选择发生改变时触发
    handleChange() {
      if (this.addFormList.goods_cat.length !== 3) {
        this.addFormList.goods_cat = [2];
        return;
      }

      // console.log(this.cateId);
    },
    // 阻止切换
    beforeLeave(activeName, oldActiveName) {
      if (oldActiveName === "0" && this.addFormList.goods_cat.length !== 3) {
        this.$message.error("请先选择商品分类");
        return false;
      }
    },
    // 获取分类参数列表
    async changeTabs() {
      if (this.activeIndex === "1") {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          { params: { sel: "many" } }
        );
        if (res.meta.status !== 200) return this.$message.error("获取参数失败");
        res.data.forEach(item => {
          item.cp1_attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
          item.cp2_attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        });
        this.manyList = res.data;
      } else if (this.activeIndex === "2") {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          { params: { sel: "only" } }
        );
        if (res.meta.status !== 200) return this.$message.error("获取属性失败");
        this.onlyList = res.data;
        console.log(this.onlyList);
      }
    },
    // 已上传图片时触发的函数
    handlePreview(file) {
      console.log(file);
      this.previewPath = file.response.data.url;
      this.picDialogVisible = true;
    },
    // 监听图片上传成功的事件
    // 在这个事件中可以获取到服务器返回回来的response数据
    handleSuccess(response) {
      console.log(response);
      // 拼接得到一个图片信息对象
      const picList = { pic: response.data.tmp_path };
      this.addFormList.pics.push(picList);
      console.log(this.addFormList);
    },
    // 删除图片时触发的函数
    handleRemove(file) {
      // console.log(file);
      const filePath = file.response.data.tmp_path;
      // console.log(filePath);
      const i = this.addFormList.pics.findIndex(x => {
        return x.pic === filePath;
      });
      console.log(i);
      this.addFormList.pics.splice(i, 1);
      console.log(this.addFormList);
    },
    // 添加商品
    add() {
      // console.log(this.addFormList);
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error("请填写必填项");
        // 请求参数必须是字符串所以需要转换
        // 但是之前的基本信息需要的是数组数组形式的 所以使用lodash 的closeDeep进行深拷贝
        var form = _.cloneDeep(this.addFormList);
        // console.log(form);
        form.goods_cat = form.goods_cat.join(",");
        // console.log(this.manyList);

        // 处理动态参数
        this.manyList.forEach(item => {
          // console.log(item);
          item.attr_vals = item.attr_vals.split(",");
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(",")
          });
          // console.log(form.attrs);
        });
        this.onlyList.forEach(item => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          });
        });
        const { data: res } = await this.$http.post("goods", form);
        if (res.meta.status !== 201) return this.$message.error("添加失败");
        this.$message.success("添加成功");
        this.$router.push("/goods");
      });
    }
    // 发起请求
    // async postAAddForm() {
    //   const { data: res } = await this.$http.post("goods", {});
    // }
  }
};
</script>

<style lang="less">
.el-steps {
  margin: 0 10px 0 0 !important;
}
.imgwidth {
  width: 100%;
}
.quill-editor {
  margin-bottom: 10px;
}
</style>
